<template>
  <Dialog v-model:visible="visible" modal :header="title" :style="{ width: '90vw' }">
    <Panel>
      <template #header>
        <div class="flex items-center gap-2">
          <span class="font-bold">Server根配置</span>
        </div>
      </template>
      listen : <InputText v-model="editingServer.listen" type="text" size="small" />
      <Divider />
    </Panel>
    <Panel>
      <template #header> Configs </template>
      <Chip v-for="(i, index) in editingServer.basicConfigs" :key="index">
        {{ i.code + '  ' + i.value + ';'
        }}<i class="pi pi-minus-circle" @click="basicConfigRemoveFn(i)" />
      </Chip>
      <Divider />
      <basic-config-add :options="options" @confirm="basicConfigAddFn"></basic-config-add>
    </Panel>
    <Divider />
    <template #footer>
      <Button label="Save" icon="pi pi-save" @click="newServerFn" />
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import BasicConfigAdd from '@/views/tools/nginx/detail-comps/basic-config-add.vue'
import type { BasicConfig, StreamServerConfig } from '@/types/dt/Dt.ts'
import { ref } from 'vue'
import { streamServerBasicOptions } from '@/views/tools/nginx/data/stream_basic_options.ts'

const visible = ref(false)

const options: { code: string; name: string }[] = [
  ...streamServerBasicOptions
]

const editingServer = ref<StreamServerConfig>({
  listen: 'localhost:8080',
  basicConfigs: [],
})
const title = ref('')
let resolve: ((a: any) => void) | undefined
let reject: ((e: Error) => void) | undefined

function basicConfigRemoveFn(e: BasicConfig) {
  editingServer.value.basicConfigs = editingServer.value.basicConfigs.filter((item) => item !== e)
}

function basicConfigAddFn(e: BasicConfig) {
  editingServer.value.basicConfigs.push(e)
}

function newServerFn() {
  if (typeof resolve === 'function') {
    resolve(JSON.parse(JSON.stringify(editingServer.value)))
  }
  visible.value = false
  editingServer.value = {
    listen: 'localhost:8080',
    basicConfigs: [],
  }
  resolve = undefined
  reject = undefined
}
function open(c?: StreamServerConfig): Promise<StreamServerConfig> {
  if (c) {
    title.value = 'Edit Stream Server'
    editingServer.value = JSON.parse(JSON.stringify(c))
  } else {
    title.value = 'Add Stream Server'
    editingServer.value = {
      listen: 'localhost:8080',
      basicConfigs: [],
    }
  }
  visible.value = true
  return new Promise((r, re) => {
    resolve = r
    reject = re
  })
}

defineExpose({
  open: open,
})
</script>
<style scoped></style>
